#include <QtCore/QTimer>
#include <QtCore/QDateTime>
#include <QtCore/QDebug>
#include <QtGui/QImage>
#include "dialog.h"
#include "ui_dialog.h"
#include "common.h"
#include "mvapi.h"

Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);
    m_timer = new QTimer(this);
    m_timer->setInterval(50);

    int nBdNum = MV_GetDeviceNumber();     //get number of mv devices.
    if(nBdNum<=0)
    {
        qDebug("No device found.");
        m_deviceHandle = NULL;
        m_imageBuffer = NULL;
    }
    else
    {
        qDebug()<<"devices:"<<nBdNum;
        m_deviceHandle = MV_OpenDevice(0, TRUE);
//        HWND hwnd=ui->mv110Widget->winId();
//        MV_SetDeviceParameter( m_deviceHandle, DISP_WHND, (DWORD)hwnd );
        MV_SetDeviceParameter(m_deviceHandle, GARB_BITDESCRIBE, DATA_aRGB8888);

        MV_IMAGEINFO info;
        MV_SetDeviceParameter(m_deviceHandle, SET_GARBIMAGEINFO, (DWORD)&info );
        qDebug()<<"info"<<info.Length<<info.nColor<<info.Heigth<<info.Width<<info.SkipPixel;
        m_imageBuffer = new uchar[info.Length];
        m_image = new QImage(m_imageBuffer, info.Width, info.Heigth, QImage::Format_RGB32);

        MV_OperateDevice(m_deviceHandle, MVRUN);

        m_timer->start();
    }

    connect(m_timer, SIGNAL(timeout()), this, SLOT(onTimeout()));

}

Dialog::~Dialog()
{
    delete ui;
}

void Dialog::onTimeout()
{
    if (m_deviceHandle == NULL)
    {
        return;
    }
    MV_IMAGEINFO info;
    MV_CaptureSingle(m_deviceHandle, FALSE, (PVOID)m_imageBuffer, m_bufferLength, &info);

    ui->label->setPixmap(QPixmap::fromImage(*m_image));
    //    m_image->save(QString("%1.png").arg(QDateTime::currentDateTime().toString("dd.MM.yyyy_hh:mm:ss.zzz")));
}

void Dialog::changeEvent(QEvent *e)
{
    QDialog::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}
